/*
	Copyright (C) 2013 Pontificia Universidad Catolica del Peru
	contact: http://avatar.inf.pucp.edu.pe/realidad-aumentada/
	address contact: Av. Universitaria 1801, San Miguel, Lima-Peru.
	
	This file is part of UbicAR PUCP.

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with This program.  If not, see <http://www.gnu.org/licenses/>.
*/
/*
	Authors: Alvaro Roger Agüero Sánchez, Rodolfo Javier Galvez Meza
	Pontificia Universidad Catolica del Peru
	Departamento de Ingeniería
*/

package org.grupoavatar.guiaubicua.punto;

import java.util.ArrayList;
import java.util.List;
import org.grupoavatar.guiaubicua.R;
import org.grupoavatar.guiaubicua.VAR;
import org.grupoavatar.guiaubicua.VDownloading;
import org.grupoavatar.guiaubicua.VInicial;
import org.grupoavatar.guiaubicua.VMapa;
import org.grupoavatar.guiaubicua.auxiliares.Red;
import org.grupoavatar.guiaubicua.auxiliares.Usuario;
import org.grupoavatar.guiaubicua.entidades.ARMarker;
import org.grupoavatar.guiaubicua.mix.DataView;
import org.grupoavatar.guiaubicua.mix.Marker;
import org.grupoavatar.guiaubicua.mix.MixContext;
import org.grupoavatar.guiaubicua.mix.data.ResultadoConsultaRating;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.google.android.maps.GeoPoint;
//import android.app.ProgressDialog;
import android.content.ComponentName;
//import android.content.Context;
import android.content.Intent;
//import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
//import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
//import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

public abstract class MasterActivity extends /*android.support.v4.app.FragmentActivity*/ SherlockFragmentActivity implements LocationListener {

	
	private LinearLayout linearLayout;
	protected Button btnGeneral;
	protected Button btnUbicacion;
	protected Button btnServicios;
	
	protected ImageView dropDownButton;
	protected LinearLayout dropDownMenu;

	protected LinearLayout subBtnMapa;
	protected LinearLayout subBtnRealidadAumentada;
	protected LinearLayout subBtnComentarios;
	protected LinearLayout subBtnComoLlegar;
	protected LinearLayout subBtnEncuestas;
	protected LinearLayout subBtnCompartir;
	
	protected Marker marker;
	protected Marker poiHijoAnterior;
	protected ArrayList<Marker> bpoi;
	protected List<Marker> markerListTemporal;

	public static Marker _poi;
	public static Marker _poiHijoAnterior;
	public static ArrayList<Marker> _bpoi;
	public static List<Marker> _markerListTemporal;
	
	/*private ProgressDialog pd;
	private LocationManager locationMgr;
	private int numeroConsultaUbicacion;
	*/
//	private MasterActivity activity;
	public ResultadoConsultaRating resultado;
	
	public void addPoi(Marker poi) {
		if (bpoi.size() > 0) {
			if (poi.getPOI().getHijos() != null && poi.getPOI().getHijos().size() > 0) {
				poiHijoAnterior = bpoi.get(0);
			}
		}
		bpoi.add(poi);
	}
	
	public static GeoPoint getPoiCoordinates(Marker poi) {
		if (poi!=null)	{
			return new GeoPoint((int) (poi.getLatitude() * 1E6), (int) (poi.getLongitude() * 1E6));
		}
		return null;
	}
	
	public static GeoPoint getPoiCoordinates() {
		if (_poi!=null)	{
			return new GeoPoint((int) (_poi.getLatitude() * 1E6), (int) (_poi.getLongitude() * 1E6));
		}
		return null;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		super.setContentView(R.layout.tab_contenedora);
		
		//activity = this;
		
		Red.pd = null;
		
		marker = _poi;
		bpoi = _bpoi;
		poiHijoAnterior = _poiHijoAnterior;
		markerListTemporal = _markerListTemporal;
		
		if (bpoi == null) {
			bpoi = new ArrayList<Marker>();
			addPoi(marker);
		}
		
//		lugar = new Lugar(poi);
//		TextView lblNombre = (TextView) findViewById(R.id.lblNombre);
//		lblNombre.setText(lugar.getNombre());
//		TextView lblCategoria = (TextView) findViewById(R.id.lblCategoria);
//		lblCategoria.setText(lugar.getCategoria());
		
		getSherlock().getActionBar().setTitle(marker.getTitle());
		getSherlock().getActionBar().setSubtitle(marker.getPOI().getCategoria().getNombre());
		getSherlock().getActionBar().setLogo(marker.getPOI().getCategoria().getIcono());
		
		linearLayout = (LinearLayout)findViewById(R.id.linearLayout);
		
		btnGeneral = (Button)findViewById(R.id.btn_general);
		btnUbicacion = (Button)findViewById(R.id.btn_ubicacion);
		btnServicios = (Button)findViewById(R.id.btn_servicios);
//		
//		dropDownButton = (ImageView) findViewById(R.id.dropDownButton);
//		dropDownMenu = (LinearLayout) findViewById(R.id.dropDownMenu);
//
//		subBtnMapa = (LinearLayout) findViewById(R.id.subBtnMapa);
//		subBtnRealidadAumentada = (LinearLayout) findViewById(R.id.subBtnRealidadAumentada);
//		subBtnComentarios = (LinearLayout) findViewById(R.id.subBtnComentarios);
//		subBtnComoLlegar = (LinearLayout) findViewById(R.id.subBtnComoLlegar);
//		subBtnEncuestas = (LinearLayout) findViewById(R.id.subBtnEncuestas);
//		subBtnCompartir = (LinearLayout) findViewById(R.id.subBtnCompartir);
//
//		dropDownButton.setOnClickListener(new OnClickListener() {
//
//			public void onClick(View v) {
//				if (dropDownMenu.getVisibility() == View.GONE) {
//					dropDownMenu.setVisibility(View.VISIBLE);
//				} else {
//					dropDownMenu.setVisibility(View.GONE);
//				}
//			}
//		});
//
//		subBtnMapa.setOnClickListener(new OnClickListener() {
//
//			public void onClick(View v) {
//				dropDownMenu.setVisibility(View.GONE);
//				verPoi("mapa");
//			}
//		});
//
//		subBtnRealidadAumentada.setOnClickListener(new OnClickListener() {
//
//			public void onClick(View v) {
//				dropDownMenu.setVisibility(View.GONE);
//				verPoi("ar");
//			}
//		});
//
//		subBtnComentarios.setOnClickListener(new OnClickListener() {
//
//			public void onClick(View v) {
//				dropDownMenu.setVisibility(View.GONE);
//				verComentarios();
//			}
//		});
//
//		subBtnComoLlegar.setOnClickListener(new OnClickListener() {
//
//			public void onClick(View v) {
//				dropDownMenu.setVisibility(View.GONE);
//				Location location = VInicial.getCurrentLocation(); 	
//				
//				if (location == null) {
//					numeroConsultaUbicacion = 0;
//					pd = new ProgressDialog(activity);
//					pd.setMessage("Obteniendo ubicación");
//					
////						pd.setButton("Cancelar", new DialogInterface.OnClickListener() 
////					    {
////					        public void onClick(DialogInterface dialog, int which) 
////					        {
////					        	String nmc = mixContext.noMarkersCheck();
////					        	if (nmc != null)
////					        		Toast.makeText(mixContext, nmc, Toast.LENGTH_LONG).show();
////					        	return;
////					        }
////					    });
//					pd.show();
//					
//					Criteria c = new Criteria();
//
//					c.setAccuracy(Criteria.ACCURACY_FINE);
//					// c.setBearingRequired(true);
//
//					locationMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//					locationMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 10, activity);
//					locationMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 10, activity);
//					
//					try {
//						Location gps = locationMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//						Location network = locationMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//						
//						 //if there are both values use the latest one
//			             if(gps!=null && network!=null){
//			                 if(gps.getTime()>network.getTime())
//			                	 VInicial.dataView.getContext().curLoc = gps;
//			                 else
//			                	 VInicial.dataView.getContext().curLoc = network;
//			             }
//						 else if (gps != null)
//							 VInicial.dataView.getContext().curLoc = gps;
//						 else if (network != null)
//							 VInicial.dataView.getContext().curLoc = network;
//					} catch (Exception ex2) {
//						ex2.printStackTrace();
//					}
//					VInicial.dataView.getContext().setLocationAtLastDownload(VInicial.dataView.getContext().curLoc);
//				} else {
//					double latitude = location.getLatitude();
//	                double longitude = location.getLongitude();
//	                comoLlegar();
//				}
//			}
//		});
//
//		subBtnEncuestas.setOnClickListener(new OnClickListener() {
//
//			public void onClick(View v) {
//				dropDownMenu.setVisibility(View.GONE);
//				verEncuesta();
//			}
//		});
//		
//		subBtnCompartir.setOnClickListener(new OnClickListener() {
//			
//			public void onClick(View v) {
//				dropDownMenu.setVisibility(View.GONE);
//				compartir();
//			}
//		});
	}
	
	protected void comoLlegar() {
		Intent intent = new Intent(Intent.ACTION_VIEW, 
                Uri.parse("http://maps.google.com/maps?saddr="/* + latitude + "," + longitude*/ +
                "&daddr=" + marker.getLatitude() + "," + marker.getLongitude() + "&dirflg=w"));
            intent.setComponent(new ComponentName("com.google.android.apps.maps", 
                "com.google.android.maps.MapsActivity"));
            startActivity(intent); 
	}

	protected void compartir() {
		// TODO Auto-generated method stub
		Intent share = new Intent(Intent.ACTION_SEND);
		share.setType("text/plain");
		share.putExtra(Intent.EXTRA_TEXT, "TEXTO_COMPARTIR" );
		startActivity(Intent.createChooser(share, "Compartir vía"));
	}
	
	

	@Override
	public void setContentView(int layoutResID) {
		linearLayout.removeAllViews();
		LinearLayout.inflate(this, layoutResID, linearLayout);
	}
	
	@Override
	public void setContentView(View view) {
		linearLayout.removeAllViews();
		linearLayout.addView(view);
	}

	@Override
	public void setContentView(View view, LayoutParams params) {
		linearLayout.removeAllViews();
		linearLayout.addView(view, params);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		//activity = this;
		if (DataView.volverInicio)	{
			finish();
			return;
		}
		
		if (DataView.viendoUnicoMarker)	{
//			VInicial.dataView.getDataHandler().setMarkerList(markerListTemporal);
//			markerListTemporal = null;
//			DataView.viendoUnicoMarker = false;
			//poi.setUnicoMarker(false);
			return;
		}
	}

	public void finish(){
		if (markerListTemporal != null)
			VInicial.dataView.getDataHandler().setMarkerList(markerListTemporal);
//		markerListTemporal = null;
		DataView.viendoUnicoMarker = false;
		if (marker != null)
			marker.setUnicoMarker(false);
		super.finish();
	}
	
	private void verPoi(String tipo) {
		marker.setUnicoMarker(true);
		List<Marker> poiList = new ArrayList<Marker>();
		poiList.add(marker);
		
		//List<Marker> markers = VInicial.dataView.getDataHandler().getMarkerList();
		//clonación de ArrayList, reactivado en onresume
//		markerListTemporal = new ArrayList<Marker>();
//		for (int i = 0; i < markers.size(); i++)	{
//			Marker m = markers.get(i);
//			markerListTemporal.add(m);
//		}
//		markerListTemporal = markers;
		//VInicial.dataView.getDataHandler().clearMarkers();
		VInicial.dataView.getDataHandler().setMarkerList(poiList);
		
		DataView.viendoUnicoMarker = true;
		pasarDatos();
		if (tipo.equals("ar"))	{
			startActivity(new Intent(VInicial.getContext(), VAR.class));
		}
		else if (tipo.equals("mapa"))	{
			startActivity(new Intent(VInicial.getContext(), VMapa.class));
		}
		
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (!bpoi.isEmpty()) {
				bpoi.remove(bpoi.size()-1);
			}
			return super.onKeyDown(keyCode, event);
		}
		return false;
	}
	
	private void verComentarios() {
		// TODO Auto-generated method stub		
		startActivity(new Intent(VInicial.getContext(), Comentarios.class));
		pasarDatos();
		overridePendingTransition(0, 0);
		finish();
		overridePendingTransition(0, 0);
	}
	
	public void pasarDatos() {
		_poi = marker;
		_bpoi = bpoi;
		_poiHijoAnterior = poiHijoAnterior;
		_markerListTemporal = markerListTemporal;
	}
	
	private void verEncuesta() {
		if (Usuario.esValido) {
			pasarDatos();
			Intent i = new Intent(this, VDownloading.class);
			i.putExtra("sigV", "encuesta");
			i.putExtra("idPOI", marker.getID());
			startActivity(i);
			
			//startActivity(new Intent(VInicial.getContext(), EncuestaIntroScreen.class));
			overridePendingTransition(0, 0);
			finish();
			overridePendingTransition(0, 0);
		} else {
			Toast.makeText(this, "Debe asociar una cuenta para realizar esta acción.", Toast.LENGTH_SHORT).show();
		}
	}
	
	public Marker getPoi() {
		return marker;
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
//		try {
//			Log.v(VInicial.TAG,
//					"Location Changed: " + location.getProvider() + " lat: "
//							+ location.getLatitude() + " lon: "
//							+ location.getLongitude() + " alt: "
//							+ location.getAltitude() + " acc: "
//							+ location.getAccuracy());
//
//			VInicial.dataView.getContext().setLocationAtLastDownload(location);
//			numeroConsultaUbicacion++;
//			
//			
//			if (pd != null && numeroConsultaUbicacion > 0) {
//				if (pd.isShowing())	{
//					try {
//						locationMgr.removeUpdates(this);
//					} catch (Exception ignore) {
//					}
//					locationMgr = null;
//					
//					double latitude = location.getLatitude();
//	                double longitude = location.getLongitude();
	                Intent intent = new Intent(Intent.ACTION_VIEW, 
	                                 Uri.parse("http://maps.google.com/maps?saddr="/* + latitude + "," + longitude*/ +
	                                 //Uri.parse("http://maps.google.com/maps?"+
	                                 "&daddr=" + marker.getLatitude() + "," + marker.getLongitude() + "&dirflg=w"));
	                intent.setComponent(new ComponentName("com.google.android.apps.maps", 
	                                 "com.google.android.maps.MapsActivity"));
//	                pd.dismiss();
//	                pd = null;
	                startActivity(intent); 
//				}
//			}
//		} catch (Exception ex) {
//			ex.printStackTrace();
//		}
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.menu.menu_detalles_poi, menu);

        return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.menuDetallesVerMapa:
				verPoi("mapa");
				break;
			case R.id.menuDetallesVerAR:
				verPoi("ar");
				break;
			case R.id.menuDetallesComentarios:
				verComentarios();
				break;
			case R.id.menuDetallesComoLlegar:
				comoLlegar();
				break;
			case R.id.menuDetallesEncuestas:
				verEncuesta();
				break;
			case R.id.menuDetallesCompartir:
				compartir();
				break;
		}
//		System.out.println("ITEM: <" + item + ">");
		return true;
	}
}
